package com.network.common;

import com.network.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class JdbcUtil
{
    @Autowired
    JdbcTemplate jdbcTemplate;

    PageResult pageResult=null;

    /**
     *
     * @param page 当前页数
     * @param limit 每页大小
     * @param select 查询字段 sql语句
     * @param from  查询表sql语句
     * @return
     */
    public PageResult pageSql(int page,int limit,String select,String from)
    {

        pageResult=new PageResult();

        //获取总条数
        StringBuilder count=new StringBuilder("select count(*) as count");
        count.append(" "+from);

        //获取列表数据
        StringBuilder listSql=new StringBuilder();
        listSql.append(select);
        listSql.append(" "+from);
        listSql.append(" limit "+page+","+limit);

        int totalSize= jdbcTemplate.queryForObject(count.toString(), Integer.class);

        if (totalSize==0)
        {
            pageResult.setCode(0);
            pageResult.setCount(0);
            pageResult.setData(null);
        }else
        {
            pageResult.setCode(0);
            pageResult.setCount(totalSize);
            List<Map<String, Object>> list=jdbcTemplate.queryForList(listSql.toString());
            pageResult.setData(list);
        }
        return pageResult;
    }
    /**
     *
     * @param page 当前页数
     * @param limit 每页大小
     * @param select 查询字段 sql语句
     * @param from  查询表sql语句
     * @param param  占位符 参数
     * @return
     */
    public PageResult pageSql(int page,int limit,String select,String from,Object[] param)
    {

        pageResult=new PageResult();

        //获取总条数
        StringBuilder count=new StringBuilder("select count(*) as count");
        count.append(" "+from);

        //获取列表数据
        StringBuilder listSql=new StringBuilder();
        listSql.append(select);
        listSql.append(" "+from);
        listSql.append(" limit "+page+","+limit);

        int totalSize= jdbcTemplate.queryForObject(count.toString(), param,Integer.class);

        if (totalSize==0)
        {
            pageResult.setCode(0);
            pageResult.setCount(0);
            pageResult.setData(null);
        }else
        {
            pageResult.setCode(0);
            pageResult.setCount(totalSize);
            List<Map<String, Object>> list=jdbcTemplate.queryForList(listSql.toString(),param);
            pageResult.setData(list);
        }
        return pageResult;
    }
}
